from django.contrib.auth.backends import ModelBackend
from users.models import User
from django.db import models
from django.contrib.auth.hashers import check_password
from django.conf import settings
from ronglian_sms_sdk import SmsSDK
import json



def jwt_response_payload_handler(token, user=None, request=None):

    return {
        'token': token,
        'user_id': user.pk,
        'username': user.username,
    }


class MyAuthentication(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):

        # 查询用户对象
        user = User.objects.filter(models.Q(username=username)|models.Q(phone=username)).first()

        # 判断用户 / 密码 / 是否是管理员
        if user and check_password(password, user.password) and user.is_staff:
            return user

        else:
            return None


# 发送短信
def send_message(sms_code, mobile, expire=5):
    # 实例化sdk
    sdk = SmsSDK(settings.ACCID, settings.AUTHTOKEN, settings.APPID)

    # 组织数据
    tid = "1"
    mobile = "%s"%mobile
    datas = ("%s"%sms_code, "%s"%expire)

    # 发送短信，并接收响应
    res = sdk.sendMessage(tid=tid, mobile=mobile, datas=datas)

    # 解析响应
    print("发送短信的响应:", res, type(res))

    res_dict = json.loads(res)
    if res_dict.get("statusCode") == "000000":
        return True
    else:
        return False
